<template>
  <div class="currency-card-list">
    <div
      v-for="(item, idx) in list"
      :key="idx"
      class="currency-card-custom"
      @click="goToQuantContractShow(item)"
    >
      <div class="card-header-custom">
        <img class="coin-icon-custom" :src="item.logo" alt="" @error="e => e.target.src = 'https://dummyimage.com/56x56/f5f5f5/cccccc&text='" />
        <div class="coin-info-custom">
          <div class="coin-symbol-custom">{{ item.showSymbol }}</div>
          <div class="coin-base-custom">USD</div>
        </div>
      </div>

      <div class="card-chart-custom">
        <div :ref="el => chartRefs[idx] = el" class="echart-custom"></div>
      </div>

      <div class="card-price-row-custom">
        <span class="price-custom" :style="getPriceColorStyle(item)">
          ${{ priceFormat(tradeStore.allCoinPriceInfo[item.coin]?.close) }}
        </span>

        <span :class="['change-custom', getChangeUp(item) ? 'up-custom' : 'down-custom']">
          <span v-if="getChangeUp(item)">▲</span><span v-else>▼</span>
          {{ tradeStore.allCoinPriceInfo[item.coin]?.priceChangePercent }}%
        </span>
      </div>

      <div class="card-btn-row-custom">
        <button class="btn-custom buy-custom">{{ _t18('option_buy_up') }}</button>
        <button class="btn-custom sell-custom">{{ _t18('option_buy_short') }}</button>
      </div>
    </div>
	

	
  </div>
  <!-- ⭐ 新增底部正方形行情宫格 -->
 <div class="square-market-grid">
   <div
     v-for="(item, idx) in bottomCoinList"
     :key="'square-' + idx"
     class="square-card"
     :style="getSquareCardStyle(item)"
     @click="goSquareToDetail(item)"  
   >
     <div class="sq-symbol" :style="{ color: getPriceColor(item) }">
      {{ item.coin.toUpperCase() }}
     </div>
 
     <div class="sq-price" :style="{ color: getPriceColor(item) }">
       {{ item.close.toFixed(2) }} 
     </div>
 
     <div class="sq-change-row">
       <span :style="{ color: getPriceColor(item) }">
         {{ item.change > 0 ? '+' : '' }}{{ item.change }}
       </span>
       <span :style="{ color: getPriceColor(item) }">
         {{ item.percent > 0 ? '+' : '' }}{{ item.percent }}%
       </span>
     </div>
   </div>
 
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { useTradeStore } from '@/store/trade/index'
import { priceFormat } from '@/utils/decimal.js'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const tradeStore = useTradeStore()
const router = useRouter()

const props = defineProps({
  list: { type: Array, required: true },
  tabIndex: { type: Number, default: 0 }
})

/* =============== 卡片图表 =============== */
const chartRefs = ref([])

function getChangeUp(item) {
  const diff =
    Number(tradeStore.allCoinPriceInfo[item.coin]?.close) -
    Number(tradeStore.allCoinPriceInfo[item.coin]?.openPrice)
  return diff >= 0
}

function getLineColor(item) {
  return getChangeUp(item) ? '#00b386' : '#ff4444'
}

function genChartData(base = 100, count = 20) {
  const arr = [base]
  for (let i = 1; i < count; i++) {
    const next = arr[i - 1] + (Math.random() - 0.5) * base * 0.7
    arr.push(Number(next.toFixed(2)))
  }
  return arr
}

function renderChart(idx, item) {
  const el = chartRefs.value[idx]
  if (!el) return

  let chart = echarts.getInstanceByDom(el)
  if (!chart) chart = echarts.init(el)

  const num = Math.floor(Math.random() * (1000 - 100 + 1)) + 100
  const data = genChartData(num, 20)

  chart.setOption({
    grid: { left: 0, right: 0, top: 12, bottom: 12 },
    xAxis: { type: 'category', show: false, data: data.map((_, i) => i) },
    yAxis: { type: 'value', show: false },
    series: [
      {
        data,
        type: 'line',
        smooth: 0.6,
        symbol: 'none',
        lineStyle: { color: getLineColor(item), width: 1.4 }
      }
    ]
  })
}

/* =============== 价格颜色快速刷新 =============== */
const prevPrices = ref({})
const priceColors = ref({})

const getPriceColorStyle = (item) => ({
  color: priceColors.value[item.coin] || '#999',
  transition: 'color 0.15s linear'
})

function setupPriceWatchers() {
  props.list.forEach(item => {
    watch(
      () => tradeStore.allCoinPriceInfo[item.coin]?.close,
      (newVal, oldVal) => {
        if (newVal == null) return

        if (!oldVal) {
          prevPrices.value[item.coin] = newVal
          priceColors.value[item.coin] = '#999'
          return
        }

        priceColors.value[item.coin] =
          newVal > oldVal ? '#00b386' :
          newVal < oldVal ? '#ff4444' : '#999'

        prevPrices.value[item.coin] = newVal
      },
      { immediate: true }
    )
  })
}

/* ============================================================
   ⭐ 底部宫格：coinType=2 → 加载时随机 10 个（只执行一次）
   ⭐ 后续完全实时跟随 WebSocket 行情变化（不再重新随机）
   ============================================================ */

/* ============================================================
   ⭐ 底部宫格：coinType=2 → 加载时随机 10 个（只执行一次）
   ⭐ 后续实时根据前后价格变化 → 改变颜色 / 背景色
   ============================================================ */

const bottomCoinList = ref([])

function loadBottomMarket() {
  const allPrice = tradeStore.allCoinPriceInfo
  const allList = tradeStore.secondContractCoinList || []
  if (!allPrice || !allList.length) return

  const type2List = allList.filter(item => Number(item.coinType) === 2)
  const arr = type2List.map(item => {
    const v = allPrice[item.coin]
    if (!v) return null
    const close = Number(v.close)
    return {
      id: item.id,           // 必须保存 id
      coin: item.coin,       // symbol
      close,
      lastPrice: close,
      open: Number(v.openPrice),
      change: close - Number(v.openPrice),
      percent: Number(v.priceChangePercent)
    }
  }).filter(Boolean)

  bottomCoinList.value = arr.sort(() => Math.random() - 0.5).slice(0, 9)
}


/* ============================================================
   ⭐ WebSocket 实时监听 → 前后对比价格 → 更新背景 & 颜色
   ============================================================ */
watch(
  () => tradeStore.allCoinPriceInfo,
  (newInfo) => {
    if (!newInfo || bottomCoinList.value.length === 0) return

    bottomCoinList.value = bottomCoinList.value.map(item => {
      const v = newInfo[item.coin]
      if (!v) return item

      const newClose = Number(v.close)
      const last = item.lastPrice

      // ⭐ 与上一秒价格比较（大卡片同款）
      let color = item.color
      if (newClose > last) color = '#00b386'
      else if (newClose < last) color = '#ff4444'

      return {
        ...item,
        close: newClose,
        lastPrice: newClose,   // ⭐ 更新 lastPrice
        color,
        open: Number(v.openPrice),
       change: Number((newClose - Number(v.openPrice)).toFixed(2)),

        percent: Number(v.priceChangePercent)
      }
    })
  },
  { deep: true }
)



/* ============================================================
   ⭐ 颜色判断（用 lastUp 来决定颜色）
   ============================================================ */
function getPriceColor(item) {
  if (item.color === '#999') {
    return '#999'   // ⭐ 灰色背景时字体变成白色
  }
  return item.color // 涨跌继续用绿/红
}



/* ============================================================
   ⭐ 背景色判断（同样用 lastUp）
   ============================================================ */
function getSquareCardStyle(item) {
  if (item.color === '#00b386') {
    return { background: 'rgba(0,200,130,0.15)' }
  }
  if (item.color === '#ff4444') {
    return { background: 'rgba(255,70,70,0.15)' }
  }
  return { background: 'rgba(150,150,150,0.15)' }
}



/* 点击宫格跳转 */
function goSquareToDetail(item) {
  router.push({
    path: '/quantContract',
    query: {
      id: item.id,        // 和大卡片一样
      symbol: item.coin   // 和大卡片一样
    }
  })
}






/* 页面加载时执行 */
onMounted(() => {
  // ⭐ 大卡片初始化：不要动
  nextTick(() => props.list.forEach((item, idx) => renderChart(idx, item)))
  setupPriceWatchers()

  // ⭐ 初始化底部宫格（必须在这里执行）
  loadBottomMarket()
})

onBeforeUnmount(() => {
  prevPrices.value = {}
  priceColors.value = {}
})

/* 大卡片点击 */
function goToQuantContractShow(item) {
  router.push({
    path: '/quantContract',
    query: { id: item.id, symbol: item.coin }
  })
}
</script>


<style scoped>
.currency-card-list {
  width: 100%;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}
.currency-card-custom {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 220px;
  position: relative;
  box-sizing: border-box;
  width: 100%;
  cursor: pointer;
}
.card-header-custom {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 12px;
}
.coin-icon-custom {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f5f5f5;
  margin-right: 14px;
  border: 2px solid #fff;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.06);
  object-fit: cover;
  display: block;
}
.coin-info-custom {
  display: flex;
  flex-direction: column;
}
.coin-symbol-custom {
  font-size: 14px;
  font-weight: bold;
  color: #222;
}
.coin-base-custom {
  font-size: 11px;
  color: #888;
  margin-top: 2px;
}
.card-chart-custom {
  width: 100%;
  height: 70px;
  margin: 10px 0 0 0;
}
.echart-custom {
  width: 100%;
  height: 70px;
}
.card-price-row-custom {
  width: 100%;
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin: 18px 0 0 0;
}
.price-custom {
  font-size: 12px;
  font-weight: 900;
  max-width: 90px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.change-custom {
  font-size: 12px;
  font-weight: 600;
  margin-left: 8px;
}
.up-custom {
  color: #00b386;
}
.down-custom {
  color: #ff4444;
}
.card-btn-row-custom {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 22px;
}
.btn-custom {
  flex: 1;
  font-size: 12px;
  font-weight: 600;
  border: none;
  border-radius: 8px;
  padding: 8px 0;
  margin: 0 4px;
  color: #fff;
  cursor: pointer;
}
.buy-custom {
  background: #00b386;
}
.sell-custom {
  background: #ff4444;
}
.btn-custom:first-child {
  margin-left: 0;
}
.btn-custom:last-child {
  margin-right: 0;
}
/* ===================
   底部正方形行情宫格
   =================== */
.square-market-grid {
  margin-top: 26px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
  width: 100%;
}

.square-card {
  border-radius:8px;
  padding: 10px 10px;
  text-align: center;
  background: #222; /* 会被动态背景覆盖 */
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  width: 100%;           /* 占满 grid 单元格 */
    min-width: 0;          /* 允许内部截断 */
    padding: 10px;
    box-sizing: border-box;
}

.sq-symbol {
  font-size: 14px;
  font-weight: 800;
  color: #fff;
  margin-bottom: 5px;
}

.sq-price {
  font-size: 16px;
  font-weight: 400;
  margin-bottom: 5px;
}

.sq-change-row {
  font-size: 11px;
  display: flex;
  justify-content: space-between;
  padding: 0 px;
  gap: 6px;
}

</style>
